package com.tangkun.environment.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.tangkun.environment.R;
import com.tangkun.environment.network.GlobalUrl;
import com.tangkun.environment.utils.LogUtils;
import com.tangkun.environment.utils.Utils;
import com.tangkun.environment.view.CustomViewPager;
import com.tangkun.environment.view.ZoomableImageView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

/**
 * @author tangkun
 * @ClassName: ClassStarImageActivity
 * @Description: TODO(荣誉堂下的相册大图列表预览删除)
 * @date 2016年3月24日 下午2:08:52
 */
public class DeleteImageActivity extends BaseActivity {
    private ImageAdapter adapter;
    private CustomViewPager pager;

    private List<File> fileList;
    private List<String> urlList;
    private List<String> deletedUrlList = new ArrayList<String>();
    private TextView headTitleTxt, doneTv;
    private ImageView headImg;
    private int index = 0;
    /**
     * 预览列表里有选中图片有变动返回码
     */
    public static int RESULT_CODE_DELETE_CHANGED = 6;


    @SuppressWarnings("unchecked")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xiangce_delete);
        fileList = (List<File>) getIntent().getSerializableExtra("fileList");
        urlList = (List<String>) getIntent().getSerializableExtra("urlList");
        index = (Integer) getIntent().getIntExtra("index", 0);

        headTitleTxt = (TextView) findViewById(R.id.head_title);
        headTitleTxt.setText("预览(" + (index + 1) + "/" + urlList.size() + ")");
        headImg = (ImageView) findViewById(R.id.img);
        doneTv = (TextView) findViewById(R.id.done_tv);

        adapter = new ImageAdapter(urlList, fileList);
        pager = (CustomViewPager) findViewById(R.id.image);
        pager.setAdapter(adapter);
        pager.setCurrentItem(index);

        initListener();

    }

    private void initListener() {
        pager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                index = arg0;
                headTitleTxt.setText("预览(" + (index + 1) + "/" + urlList.size() + ")");
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });

        // 下载图片
        // final Button button = (Button) findViewById(R.id.button);
        // button.setOnClickListener(new View.OnClickListener() {
        //
        // @Override
        // public void onClick(View arg0) {
        // try {
        // DownloadAsyncTask task = new DownloadAsyncTask(button, new
        // File(Helper.getRootPath(), "/download/" + new
        // SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg"));
        // task.execute(new URL(urlList.get(pager.getCurrentItem())));
        // } catch (Exception e) {
        //
        // }
        // }
        // });

        // 返回键 这里返回时会监听相册中选中的图片数据
        ((ImageView) findViewById(R.id.back)).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                finish();
            }
        });

        // 删除图片按钮
        headImg.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                deletedUrlList.add(urlList.get(index));
                urlList.remove(index);
                fileList.remove(index);
                if (urlList.size() <= 0) {
                    Intent intent = new Intent();
                    intent.putStringArrayListExtra("newDeletedSet", (ArrayList<String>) deletedUrlList);
                    intent.putStringArrayListExtra("urlList", (ArrayList<String>) urlList);
                    intent.putExtra("fileList", (ArrayList<File>) fileList);
                    setResult(RESULT_CODE_DELETE_CHANGED, intent);
                    finish();
                } else {
                    headTitleTxt.setText("预览(" + (index + 1) + "/" + urlList.size() + ")");
                    if (index > 0) {
                        index--;
                    }
                    adapter.notifyDataSetChanged();
                }
            }
        });

        // 完成按钮
        doneTv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO 完成按钮监听事件
                Intent intent = new Intent();
                intent.putStringArrayListExtra("newDeletedSet", (ArrayList<String>) deletedUrlList);
                intent.putStringArrayListExtra("urlList", (ArrayList<String>) urlList);
                intent.putExtra("fileList", (ArrayList<File>) fileList);
                setResult(RESULT_CODE_DELETE_CHANGED, intent);
                finish();
            }
        });
    }

    private class DownloadAsyncTask extends AsyncTask<URL, Integer, Void> {

        private Button button;
        private Context context;
        private File file;

        public DownloadAsyncTask(Button button, File file) {
            this.button = button;
            this.context = button.getContext();
            this.file = file;
        }

        @Override
        protected void onPreExecute() {
            button.setEnabled(false);
        }

        @Override
        protected Void doInBackground(URL... params) {
            URL url = params[0];

            try {
                URLConnection conn = url.openConnection();
                conn.connect();

                long fileSize = conn.getContentLength();
                if (fileSize <= 0) {
                    Toast.makeText(context, "无法获知图片大小", Toast.LENGTH_SHORT).show();
                    cancel(true);
                    return null;
                }
                InputStream is = conn.getInputStream();
                if (is == null) {
                    Toast.makeText(context, "图片下载失败", Toast.LENGTH_SHORT).show();
                    cancel(true);
                    return null;
                }

                if (file.getParentFile().exists() == false) {
                    file.getParentFile().mkdirs();
                }

                OutputStream os = new FileOutputStream(file);
                publishProgress(0);

                byte buf[] = new byte[1024];
                int readed = -1, readedTotal = 0;
                while ((readed = is.read(buf)) != -1) {
                    os.write(buf, 0, readed);

                    readedTotal += readed;
                    publishProgress((int) (100 * readedTotal / fileSize));
                }
                publishProgress(100);
                is.close();
                os.close();
            } catch (Exception e) {
                Toast.makeText(context, "图片下载失败", Toast.LENGTH_SHORT).show();
            }
            return null;
        }

        @Override
        protected void onCancelled(Void v) {
            button.setEnabled(true);
        }

        @Override
        protected void onPostExecute(Void v) {
            button.setEnabled(true);
            try {
                MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getPath(), file.getName(), "");

                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
            } catch (Exception e) {

            }
            Toast.makeText(context, "图片已下载", Toast.LENGTH_SHORT).show();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
        }
    }

    public void setUrlList(List<String> urlList) {
        adapter.setUrlList(urlList);
        adapter.notifyDataSetChanged();
    }

    private class ImageAdapter extends PagerAdapter {

        private List<String> urlList;
        private List<File> fileList;

        public ImageAdapter(List<String> urlList, List<File> fileList) {
            this.urlList = urlList;
            this.fileList = fileList;
        }

        public List<String> getUrlList() {
            return urlList;
        }

        public void setUrlList(List<String> urlList) {
            this.urlList = urlList;
        }

        @Override
        public int getCount() {
            return urlList == null ? 0 : urlList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object obj) {
            return view == (View) obj;
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            View v = getLayoutInflater().inflate(R.layout.pic_list, null);
            final ZoomableImageView imageView = (ZoomableImageView) v.findViewById(R.id.imageView);
//            Bitmap bitmap = null;
//            try {
////                bitmap = Utils.decodeFile(fileList.get(position).getPath());
//                bitmap = Utils.getBitmapFromUrl(urlList.get(position));
//            } catch (Exception e) {
//
//            }
//            if (bitmap != null) {
//                imageView.setImageBitmap(bitmap);
//            }

            if (!urlList.get(position).contains("/storage/emulated") && (urlList.get(position).toString().endsWith(".png") || urlList.get(position).toString().endsWith(".jpg"))) {
                //表示网络半路径
                //refer to blog http://blog.csdn.net/qq_19711823/article/details/50856236
                LogUtils.e("DeleteImageActivity 网络图片全路径:" + GlobalUrl.IMG_URL + urlList.get(position));
                Glide.with(DeleteImageActivity.this).load(GlobalUrl.IMG_URL + urlList.get(position)).asBitmap().into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        imageView.setImageBitmap(resource);
                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        super.onLoadFailed(e, errorDrawable);
                        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_place_holder);
                        imageView.setImageBitmap(bitmap);
                    }
                });
            } else {
                //表示本地文件地址
                Bitmap bitmap = BitmapFactory.decodeFile(urlList.get(position).toString());
                imageView.setImageBitmap(bitmap);

//                imageView.setImageBitmap(Utils.getImageThumbnail(urlList.get(position).toString(),200,200));

//                try {
//                    Bitmap bitmap = Utils.getBitmapFromUrl(urlList.get(position).toString());
//                    LogUtils.e("DeleteImageActivity 本地图片全路径:" + urlList.get(position) + "  to bitmap isNull:" + (bitmap == null));
//                    imageView.setImageBitmap(bitmap);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    LogUtils.e("DeleteImageActivity getBitmapFromUrl Exception:" + e.toString());
//                }
            }

            ((ViewPager) container).addView(v, 0);
            return v;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        pager.removeAllViews();
    }

}
